package juc.flowcontrol.cyclicbarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author fangbin
 * @desc
 * @date 2020/6/26 22:20
 */
public class CyclicBarrierDemo {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println("达到五个，开始执行");
            }
        });
        for(int i=0;i<10;i++){
            new Thread(new Task(i,cyclicBarrier)).start();
        }
    }
}

class  Task implements Runnable{

    private CyclicBarrier cyclicBarrier;
    private Integer id;

    public Task(Integer id,CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
        this.id = id;
    }

    @Override
    public void run() {
        System.out.println("线程"+id+"正在前往集合地点");
        try {
            Thread.sleep((long)Math.random()*10000);
            System.out.println("线程"+id+"已经到达集合地点，开始等待其他人到达");
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }

    }
}